package com.ygqh.baby.service;

import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.MsgModel;
import com.ygqh.baby.model.OrderDeliverModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.KdNiaoUtil;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class OrderSendHandler {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private YgLogisticsService ygLogisticsService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private YgReturnOrderService ygReturnOrderService;
    @Autowired
    private YgReturnOrderLogService ygReturnOrderLogService;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private AppMessageService appMessageService;
    @Autowired
    private YgReturnOrderDetailService ygReturnOrderDetailService;

    @Value("${promotion.link}")
    protected String promotionLink;

    public void send(List<OrderDeliverModel> orderDeliverModels) {

        Iterator<OrderDeliverModel> it = orderDeliverModels.iterator();

        List<YgOrderLog> orderLogs = new ArrayList<>();
        List<YgReturnOrderLog> returnLogs = new ArrayList<>();
        MsgModel msg = new MsgModel();

        List<YgOrder> orderList = new ArrayList<>();
        List<YgReturnOrder> changeList = new ArrayList<>();
        List<YgLogistics> logisticsList = new ArrayList<>();
        while (it.hasNext()) {
            try {
                OrderDeliverModel next = it.next();
                YgLogistics l = next.getYgLogistics();
                String orderCode = l.getOrderId();
                Boolean logisticsExist = ygLogisticsService.isExist(orderCode, l.getExpressCode());
                if (logisticsExist) {
                    it.remove();
                    continue;
                }
                Boolean orderExist = true;

                if (!next.isChange()) {

                    orderExist = ygOrderService.isExist(Long.parseLong(orderCode));
                } else {
                    orderExist = ygReturnOrderService.isExist(l.getOrderId(), ReturnType.Change);
                }
                if (!orderExist) {
                    it.remove();
                    continue;
                }

                if (!next.isChange()) {
                    this.orderSend(next, orderList, orderLogs);
                } else {
                    this.changeSend(next, changeList, returnLogs, orderList);
                }

                l.setUserId(next.getUser().getId());

                logisticsList.add(l);

                this.buildSendMsg(next, msg);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("订单发货异常。" + ExceptionUtil.getExceptionMsg(e));
            }
        }

        ygLogisticsService.addLogisticsBatch(logisticsList);
        this.updateOrderSend(orderList);
        ygOrderLogService.addOrderLogBatch(orderLogs);
        this.updateChangeSend(changeList);
        ygReturnOrderLogService.addBatch(returnLogs);
        scheduleJobService.addBalanceJobBatch(orderList, "OrderSendHandler.send");
        KdNiaoUtil.kdNiaoSubscribe(logisticsList);
        sendOrderSendMsg(msg);

    }

    private void updateOrderSend(List<YgOrder> orderList) {

        List<YgOrderDetail> odList = new ArrayList<>();
        orderList.forEach(o -> {
            odList.addAll(o.getOrderDetail());
        });

        ygOrderService.updateStatus4SendByTask(orderList, odList);
    }

    private void updateChangeSend(List<YgReturnOrder> changeList) {

        List<YgReturnOrderDetail> odList = new ArrayList<>();
        changeList.forEach(o -> {
            odList.addAll(o.getReturnOrderDetails());
        });

        ygReturnOrderService.updateChangeSend(changeList);
        ygReturnOrderDetailService.updateSendBatch(odList);
    }

    private void buildSendMsg(OrderDeliverModel next, MsgModel msg) {

        String productNames = next.getProductNames();
        YgLogistics l = next.getYgLogistics();
        YgUser user = next.getUser();
        if (user == null || StringUtils.isBlank(user.getOpenId())) {
            return;
        }

        String url = promotionLink + "/user/orderdetail.html?orderId=" + l.getOrderId();
        String title = "亲，您购买的壹果商品已经发货啦！收到商品后请给予评价哦！";

        String orderType = "order";
        if (next.isChange()) {

            url = promotionLink + "/return/viewProgress.html";
            title = "亲，您的换货商品已经发出啦，感谢您对壹果的支持。";
            orderType = "change";
        }

        TemplateMessage orderSendMsg = getWxSendMsg(title, url, user.getOpenId(), l.getOrderId(), productNames, l);
        if (orderSendMsg != null && YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
            String mobileTitle = "亲，您购买的壹果商品已经发货啦！收到商品后请给予评价哦！商品持续上新中，希望您继续关注壹果！";
            YgMobile mobileMsg = new YgMobile(Long.parseLong(user.getUserName()), mobileTitle);
            msg.putMobileMsg(mobileMsg);
        }
        msg.putWxMsg(orderSendMsg);

        // app 消息
		/*Map<String, String> appMsg = new HashMap<>();
		appMsg.put("orderId", l.getOrderId());
		appMsg.put("userId", user.getId().toString());
		appMsg.put("orderType", orderType);
		msg.putAppMsg(appMsg);*/
    }

    private void orderSend(OrderDeliverModel deliverRequest, List<YgOrder> orderList, List<YgOrderLog> orderLogList) {
        YgLogistics l = deliverRequest.getYgLogistics();
        List<Long> detialIds = deliverRequest.getDetailIds();
        String orderId = l.getOrderId();
        YgOrder ygOrder = ygOrderService.findOrderDetailByOrderId(Long.parseLong(orderId));
        YgUser user = ygUserService.findById(ygOrder.getUserId());
        deliverRequest.setUser(user);
        List<YgOrderDetail> orderDetail = ygOrder.getOrderDetail();

        String productNames = "";

        StringBuffer sb = new StringBuffer();

        Iterator<YgOrderDetail> it = orderDetail.iterator();
        while (it.hasNext()) {
            YgOrderDetail next = it.next();
            if (OrderDetailStatus.WaitingSend.equals(next.getDetailStatus()) && RefundStatus.NoRefund.equals(next.getRefundStatus())) {
                next.setDetailStatus(OrderDetailStatus.WaitingSign);
            }
            next.setSendMark(l.getExpressCode());
            if (CollectionUtils.isNotEmpty(detialIds)) {
                if (detialIds.contains(next.getId())) {
                    sb.append(next.getProductName() + ",");
                } else {
                    it.remove();
                }
            } else {
                sb.append(next.getProductName() + ",");
            }

        }
        productNames = sb.substring(0, (sb.length() - 1));
        deliverRequest.setProductNames(productNames);

        l.setReceiver(ygOrder.getReceiver());
        l.setPhone(ygOrder.getTelPhone());
        l.setProvinceName(ygOrder.getProvinceName());
        l.setCityName(ygOrder.getCityName());
        l.setAreaName(ygOrder.getAreaName());
        l.setAddress(ygOrder.getAddress());

        ygOrder.setSendTime(l.getSendTime());
        if (OrderStatus.WaitingSend.equals(ygOrder.getOrderStatus()) || OrderStatus.WaitingSign.equals(ygOrder.getOrderStatus())) {
            ygOrder.setOrderStatus(OrderStatus.WaitingSign);
        } else {
            logger.error("订单发货异常：【" + orderId + "】订单当前状态为: " + ygOrder.getOrderStatus());
            YgOrderLog log = new YgOrderLog(Long.parseLong(orderId), ygOrder.getOrderStatus(), "定时任务，同步订单发货状态，当前订单状态异常", "系统定时任务", new Date());
            orderLogList.add(log);
        }

        orderList.add(ygOrder);
        YgOrderLog log = new YgOrderLog(Long.parseLong(orderId), OrderStatus.WaitingSend, "定时任务，同步订单发货状态", "系统定时任务", new Date());
        orderLogList.add(log);

    }

    private void changeSend(OrderDeliverModel deliverRequest, List<YgReturnOrder> changeList, List<YgReturnOrderLog> orderLogList, List<YgOrder> orderList) {

        YgLogistics l = deliverRequest.getYgLogistics();
        List<Long> detialIds = deliverRequest.getDetailIds();

        String orderCode = l.getOrderId();
        YgReturnOrder ro = ygReturnOrderService.findDetailByReCode(orderCode);
        YgUser user = ygUserService.findById(ro.getUserId());
        deliverRequest.setUser(user);

        List<YgReturnOrderDetail> rods = ro.getReturnOrderDetails();

        String productNames = "";

        StringBuffer sb = new StringBuffer();

        Iterator<YgReturnOrderDetail> it = rods.iterator();
        while (it.hasNext()) {
            YgReturnOrderDetail next = it.next();
            next.setDetailStatus(OrderDetailStatus.WaitingSign);
            next.setSendMark(l.getExpressCode());
            if (CollectionUtils.isNotEmpty(detialIds)) {
                if (detialIds.contains(next.getId())) {
                    sb.append(next.getProductName() + ",");
                    next.setDetailStatus(OrderDetailStatus.WaitingSign);
                    next.setSendMark(l.getExpressCode());
                } else {
                    it.remove();
                }
            } else {
                sb.append(next.getProductName() + ",");
            }

        }

        productNames = sb.substring(0, (sb.length() - 1));

        deliverRequest.setProductNames(productNames);

        l.setReceiver(ro.getReceiver());
        l.setPhone(ro.getTelPhone());
        l.setProvinceName(ro.getProvinceName());
        l.setCityName(ro.getCityName());
        l.setAreaName(ro.getAreaName());
        l.setAddress(ro.getAddress());

        YgOrder order = ygOrderService.findOrderDetailByOrderId(ro.getOrderId());
        if (OrderStatus.WaitingSend.equals(order.getOrderStatus())) {
            order.setOrderStatus(OrderStatus.WaitingSign);
            order.setSendTime(l.getSendTime());
            orderList.add(order);
        }
        Iterator<YgOrderDetail> iterator = order.getOrderDetail().iterator();

        while (iterator.hasNext()) {
            YgOrderDetail od = iterator.next();
            Boolean exist = false;
            for (YgReturnOrderDetail rod : rods) {
                if (rod.getSourceSkuId().equals(od.getSkuId())) {
                    exist = true;
                    od.setSendMark(l.getExpressCode());
                    od.setDetailStatus(OrderDetailStatus.WaitingSign);
                }
            }
            if (!exist) {
                iterator.remove();
            }

        }
        if (ReturnStatus.WaitingSend.equals(ro.getReturnStatus())) {
            ro.setReturnStatus(ReturnStatus.WaitingSign);
            ro.setSendTime(l.getSendTime());
            Long sendCount = ro.getSendCount() == null ? 0L : ro.getSendCount();
            ro.setSendCount(sendCount + rods.size());

            YgReturnOrderLog log = new YgReturnOrderLog(orderCode, "发货后7天完成，感谢您对我们工作的支持。", ReturnStatus.WaitingSign, "changeSend", null);
            orderLogList.add(log);
            changeList.add(ro);

        }

    }

    private TemplateMessage getWxSendMsg(String title, String url, String openId, String orderCode, String productNames, YgLogistics l) {
        if (StringUtil.isBlank(productNames)) {
            return null;
        }
        url = promotionLink + "/return/viewProgress.html";
        title = "亲，您的换货商品已经发出啦，感谢您对壹果的支持。";
        title = "亲，您购买的壹果商品已经发货啦！收到商品后请给予评价哦！";

        String tempId = wxMpMessageService.getWxMsgTempId(WxMessageType.WaitingSign);
        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("delivername", "#323232", l.getExpressCompany());
        tplMessage.pushItem("ordername", "#323232", l.getLogisticsCode());
        tplMessage.pushItem("remark", "#323232", "订单编号：" + orderCode + "\n" + "商品名称：" + productNames);
        return tplMessage;
    }

    private void sendOrderSendMsg(MsgModel msgModel) {
        List<TemplateMessage> wxMsgList = msgModel.getWxMsgList();
        List<YgMobile> mobileMsgList = msgModel.getMobileMsgList();
        List<Map<String, String>> appMsgList = msgModel.getAppMsgList();

        if (CollectionUtils.isNotEmpty(wxMsgList)) {

            for (TemplateMessage msg : wxMsgList) {
                if (msg == null) {
                    continue;
                }
                wxMpMessageService.sendTemplateMessage(msg);
            }
        }
        if (CollectionUtils.isNotEmpty(mobileMsgList)) {

            for (YgMobile ygMobile : mobileMsgList) {
                if (ygMobile == null) {
                    continue;
                }
                try {
                    smsService.sendSms(ygMobile.getMobile().toString(), ygMobile.getContent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (CollectionUtils.isNotEmpty(appMsgList)) {
            for (Map<String, String> map : appMsgList) {
                String orderId = map.get("orderId");
                String userId = map.get("userId");
                String orderType = map.get("orderType");
                appMessageService.sendOrderDeliveryNotice(orderId, userId, orderType, null);
            }
        }
    }

    ;

}
